import util from 'util'

var filtertype={
    charsOptions:[
        { value: '2', label: '包含' },
        { value: '3', label: '不包含' },
        { value: '4', label: '开头包含' },
        { value: '5', label: '结尾包含' },
        { value: '0', label: '等于' },
        { value: '1', label: '不等于' },
        { value: '6', label: '不为空' },
        { value: '7', label: '为空' },
    ],
    numOptions:[
        { value: '8', label: '大于' },
        { value: '9', label: '小于' },
        { value: '10', label: '大于等于' },
        { value: '11', label: '小于等于' },
        { value: '12', label: '区间' },
        { value: '0', label: '等于' },
        { value: '1', label: '不等于' },
        { value: '6', label: '不为空' },
        { value: '7', label: '为空' },
    ],
    dataOptions:[
        { value: '8', label: '大于' },
        { value: '9', label: '小于' },
        { value: '10', label: '大于等于' },
        { value: '11', label: '小于等于' },
        { value: '12', label: '区间' },
    ]
}
var chartUtil={
    //类型转换，方便提示  tool
    convertData :function(data) {
        var res = [];
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            for(var j =0;j<item.source.length;j++){
                var names = item.source[j][0];
                var geoCoord =this.getMapCoord(names);
                if(geoCoord){
                    var index= util.util.getArrayIndexByOptions(res,{'name':names},['name']);
                    var datas =index==-1?{name: names,value: geoCoord}:res[index];
                    datas.value.push({
                        name:item.dimensions[1],
                        value:item.source[j][1]
                    })
                    if(index==-1){
                        res.push(datas);
                    }
                }else{
                    console.warn('地图数据转化部分数据没有经纬度信息：'+names)
                }
            }
        }
        return res;
    },
    getMapCoord(name){
        var item = chartCoordMap[name];
        if(!item){
            item=chartCoordMap[name.replace(new RegExp('市|县','g'),'')];
        }
        if(item){
            return util.util.cloneObj(item);
        }
        return null;
    },
    //地图  气泡展示大小设置
    mapSeries:function(dataset){
        var max,min;
        var list =dataset.concat();
        //step:1
        //求数据的最大最小值，来规划地图上面气泡大小，最大50  最小为10
        for(var i =0;i<list[0].source.length;i++){
            var sum =0;
            for(var j=0;j<list.length;j++){
                var geoCoord = this.getMapCoord(list[j].source[i][0]);
                if(geoCoord){
                    sum+=list[j].source[i][1];
                }
            }
            max =(max < sum || max ==null)?sum:max;
            min =(min == null || min >sum) ? sum :min;
        }
        // console.log(dataset,min,max);
        var series ={
            type: 'scatter',
            coordinateSystem: 'geo',
            data: this.convertData(list),
            symbolSize:  function(val){
                //step：2  气泡大小  比例  
                //15-50  区分  35等分
                var step = (max -min)/35;
                val =val.concat();
                var sum =0;
                for(var i =2;i<val.length;i++){
                    sum+=val[i].value;
                }
                return (15+(sum-min)/step)
            },
            symbol: 'pin'
        }
        return series;
    },
    //判断数据  是否符合地图标准，数据是否是市县可以展示地图的标准形式
    judgeMapData(dataset){
        if(dataset!=null &&  dataset.length>0){
            for(var i in dataset[0].source){
                if(this.getMapCoord(dataset[0].source[i][0])!=null){
                    return true;
                }
            }
        }
        return  false;
    }
};



//chartOptions---------------------------------start -----------------------------------------------------------------------------------

var initdata={
    "legend":{

    },
    "tooltip":{

    },
    "dataset":[
    ],
    "series":[
    ],
    "title":{
        "text":"",
        "subtext":"",
        "textAlign":"center",
        "left":"10%"
    }
}
function chartOptions(_this,config){
    this._this =_this;
    if(config ==null){
        return ;
    }
    //默认配置
    var initconfig={
        //缩略图 默认数据大于多少数据 ，出现缩略滚动条
        zoomNum:15,
        //当前 图表类型
        type:'',
        //维度 几个
        groupnum:'',
        //数值  几个
        clomnnum:'',
        //
        extendState:false
    };
    util.util.extendObj(initconfig,config);
    console.log(initconfig)
    for(var i in initconfig){
        if(initconfig[i]===''){
            console.error('参数:'+i+'不能为空')
            return ;
        }
        this[i]=initconfig[i];
    }

    if(this.clomnnum==0){
        this.clomnnum=1;
    } 
    if(this.groupnum==2 && this.clomnnum==0){
        this.clomnnum=2;
    }
    
    //维度  双维度  默认数据合并等规则   start ---------------
    this.initdata={
        onexAxis: [
            {
                type: 'category',
                show:true,
                onZeroAxisIndex :0,
                axisLine: {
                    onZero: false
                },
                axisLabel :{
                    rotate : '0',
                    fontSize : '12',
                    // formatter: function (value, index) {
                    //     return   value.indexOf('_')==-1?value:value.substring(0,value.indexOf('_'));
                    // }
                },
            }
        ],
        twoxAxis: [
            {
                type: 'category',
                show:true,
                onZeroAxisIndex :0,
                axisLine: {
                    onZero: false
                },
                axisLabel :{
                    fontSize : '12',
                    formatter: function (value, index) {
                        if(value!=null){
                            return   value.indexOf('_')==-1?value:value.substring(0,value.indexOf('_'));

                        }
                    },
                    interval:function(index, value){
                        // var its=echarts.getInstanceByDom(_this.$el.children[0]).getOption();
                        var datas =_this.graphOptions.dataset.source;
                        var list =[];
                        for(var i =0;i<datas.length;i++){
                            list.push(datas[i][0]);
                        }
                        var first =-1;
                        for(var i =0;i<list.length;i++){
                            if(list[i]==value){
                                first=i;
                                break;
                            }
                        }
                        var result =(first)==index?true:false;
                        return result;
                    },
                }
            },
            {
                type: 'category',
                show:true,
                axisLine: {
                    onZero: true
                },
                position :'bottom',
                offset :30,
                splitArea :{
                    show:true,
                    showMaxLabel :false,
                },
                axisLabel :{
                    showMinLabel:true,
                    showMaxLabel :true,
                    rotate : '0',
                    // fontFamily : 'SimSun',
                    fontSize : '12',
                    interval:(index, value)=>{
                        var its=_this.graphOptions;
                        var list ;
                        if(_this.graphType.indexOf('bar_type')==-1){
                            //正常的x和y轴
                            list=its.xAxis[1].data;
                        }else{
                            //条形图  横向xy
                            list=its.yAxis[1].data;
                        }
                        var first =-1;
                        for(var i =0;i<list.length;i++){
                            if(list[i]==value){
                                first=i;
                                break;
                            }
                        }
                        var result =(first)==index?true:false;
                        return result;
                    },
                },
                axisTick:{
                    show:true,
                    length:40
                }
            }
        ],
    }
    //维度  双维度  默认数据合并等规则   e n d ---------------

    this.createOptions();
    // return  this.options;
}
/*
初始化的options  set到vue 挂在监听数据上，触发图表的监听和绘图
 */
chartOptions.prototype.initChartOptions=function(){
    var _this =this._this;
    console.log(3,this.options)
    if(this.extendState){
        //编辑回显 初始化的时候，由于function无法保存，只需要重新  set  function
        function setfunction (source ,newdata){
            for (var property in newdata) {
                if(property !='dataset' && property!='title'){
                    if(typeof newdata[property] === "object" ){
                        if(typeof   newdata[property] === "Array" && newdata[property].length>0 && 
                            typeof   newdata[property][0] === "object"){
                            setfunction(source[property],newdata[property]);
                        }else{
                            source[property] =newdata[property]
                        }
                        
                    }else  if(typeof newdata[property] === "function" ){
                        source[property] =newdata[property]
                    }
                }
                
            }
        }
        setfunction(_this.graphOptions,this.options);
        
    }else{
        for(var i in _this.graphOptions){
            var has =false;
            for(var  j in this.options){
                if(i== j){
                    has=true;
                    if(i!='dataset' && i!='title'){
                        _this.$set(_this.graphOptions,i,util.util.cloneObj(this.options[i]));
                    }
                }
            }
            if(!has){
                delete _this.graphOptions[i];
            }
        }
        for(var i in this.options){
            var has=false;
            for(var j in _this.graphOptions){
                if(j==i){
                    has =true;
                }
            }
            if(!has){
                _this.$set(_this.graphOptions,i,this.options[i]);
            }
        }
    }
    
    console.log('处理完毕：',this.extendState,JSON.stringify(_this.graphOptions))
}

chartOptions.prototype.getOptions=function(){
    return this.options;
}



//图表初始化相关函数     start --------------------------------------------------------------
chartOptions.prototype.initX=function(){
    var _this =this._this;
    var x;
    if(this.groupnum==1){
        x=util.util.cloneObj(this.initdata.onexAxis)
    }else if(this.groupnum ==2){
        x =util.util.cloneObj(this.initdata.twoxAxis);
        x[1].data=_this.graphOptions.dataset.xdata;
    }
    return x;
},
chartOptions.prototype.initY=function(){
    var  yarr=[];
    for(var  i =0;i<this.clomnnum;i++){
        yarr.push({
            type: 'value',
            axisLabel: {
                formatter: '{value}'
            }
        });
    }
    return yarr;
}
/**
 * 图表类型  和相关样式设置  切换初始化数据内容
 */
chartOptions.prototype.initSeries=function(type){
    var arr =[];
    for(var  i =0;i<this.clomnnum;i++){
        if (type instanceof Object){
            arr.push(util.util.cloneObj(type));    
        }else{
            arr.push({type:type});
        }
    }
    return arr;
}
/**
 * 图表缩略图是否展示
 */
chartOptions.prototype.initDataZoom=function(){
    var _this =this._this;
    var hasZoom =false;
    
    if(_this.graphOptions.dataset instanceof Array){
        if(_this.graphOptions.dataset[0].source.length>this.zoomNum){
            hasZoom =true;
        }
    }else if(_this.graphOptions.dataset !=null  && _this.graphOptions.dataset.source instanceof Array 
            && _this.graphOptions.dataset.source.length>this.zoomNum){
        hasZoom =true;
    }
    if(hasZoom){
        return  [{
            show: true,
            xAxisIndex:this.groupnum===2?[0, 1]:[0],
            yAxisIndex:this.groupnum===2?[0, 1]:[0],
            start: 0,
            end: 20
        }];
    }
    return null;
}
//图表初始化相关函数     end --------------------------------------------------------------



chartOptions.prototype.initOptions={
    initPie(){
        //普通饼图
        this.options.series.push({type:"pie"});
    },
    initFunnel(){
        //漏斗图
        this.options.series.push({"type":"funnel"});
    },
    initMap(){
        //地图
        var _this =this._this;
        this.options.tooltip.formatter= function(params, ticket, callback) {
            if(params.seriesType=='scatter' && params.value.length>2){
                var arr =params.value.concat();
                arr.splice(0,2);
                var sum =0;
                var res =params.name+'<br />';
                for(var i in arr){
                    sum+=arr[i].value;
                    res += arr[i].name+':'+arr[i].value+'<br />';
                }
                res+='合计：'+sum;
                return res;
            }
        }
        this.options.geo ={
            map: 'china',
            roam: true,
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        // color: 'rgba(0,0,0,0.4)'
                    }
                }
            },
            itemStyle: {
                normal:{
                    // borderColor: 'rgba(0, 0, 0, 0.2)'
                },
                emphasis:{
                    areaColor: null,
                    shadowOffsetX: 0,
                    shadowOffsetY: 0,
                    shadowBlur: 20,
                    borderWidth: 0,
                    // shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
        this.options.series =[chartUtil.mapSeries(_this.graphOptions.dataset)];
    },
    initBar(){
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =x;
        this.options.yAxis= y;
        this.options.series=this.initSeries('bar');
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].yAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initBar_type(){
        //条形图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =y;
        this.options.yAxis= x;
        this.options.series=this.initSeries('bar');
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].xAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initline(){
        //线图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =x;
        this.options.yAxis= y;
        this.options.series=this.initSeries('line');
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].yAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initscatter(){
        //散点图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =x;
        this.options.yAxis= y;
        this.options.series=this.initSeries('scatter');
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].yAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initline_area(){
        //折线面积图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =x;
        this.options.yAxis= y;
        this.options.series=this.initSeries({
            type: 'line',
            areaStyle:{}
        });
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].yAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initbar_pile(){
        //柱状堆叠图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =x;
        this.options.yAxis= y;
        this.options.series=this.initSeries({
            type: 'bar',
            stack:"all"
        });
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].yAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initbar_type_pile(){
        //条形堆叠图
        var x =this.initX();
        var y =this.initY();
        this.options.xAxis =y;
        this.options.yAxis= x;
        this.options.series=this.initSeries({
            type: 'bar',
            stack:"all"
        });
        var zoom= this.initDataZoom();
        if(zoom){
            delete zoom[0].xAxisIndex;
            this.options.dataZoom =zoom;
        }
    },
    initpie_more(){
        //嵌套环线 饼图
    },
    initTree(){
        //树图

    }
};
chartOptions.prototype.createOptions=function(){
    var _this =this._this;
    this.options =util.util.cloneObj(initdata);
    this.init ;
    switch(this.type){
        case 'pie':
            this.init=this.initOptions.initPie;
        break;
        case 'funnel':
            this.init=  this.initOptions.initFunnel;
        break;
        case 'map':
            this.init=this.initOptions.initMap;
        break;
        case 'tree':
            this.init=this.initOptions.initTree;
        break;
        case 'bar':
            this.init=this.initOptions.initBar;
        break;
        case 'bar_type':
            this.init=this.initOptions.initBar_type;
        break;
        case 'line':
            this.init=this.initOptions.initline;
        break;
        case 'line_area':
            this.init=this.initOptions.initline_area;
        break;
        case 'bar_pile'://柱状堆叠图
            this.init=this.initOptions.initbar_pile;
        break;
        case 'bar_type_pile'://条形堆叠图
            this.init=this.initOptions.initbar_type_pile;
        break;
        case 'scatter'://条形堆叠图
            this.init=this.initOptions.initscatter;
        break;
        case 'pie_more':
            this.init=this.initOptions.initpie_more;
        break;
    }
    if(this.init!=null){
        this.init();
        for(var i  in this.options.series){
            if(_this.graphOptions.dataset instanceof Array){
                this.options.series[i].datasetIndex=i;
            }else{
                this.options.series[i].datasetIndex=0;
            }
        }
    }
    

}
//chartOptions---------------------------------end  -----------------------------------------------------------------------------------
export {
    filtertype,chartUtil,chartOptions
};
